package top.util.concurrent.queue;

import java.util.AbstractQueue;
import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author He Kuntao
 * @since 2025/6/10 14:09
 */
public class FArrayBlockingQueue<E> extends AbstractQueue<E> implements BlockingQueue<E> {

    /**
     * 队列元素
     */
    final Object[] items;

    /**
     * 可重入锁
     */
    final ReentrantLock lock;

    /**
     * 等待 takes 的条件
     */
    private final Condition notEmpty;

    /**
     * 等待 puts 的条件
     */
    private final Condition notFull;

    /**
     * items index for next put, offer, or add
     */
    int putIndex;

    /**
     * items index for next take, poll, peek or remove
     */
    int takeIndex;

    /**
     * 队列中的元素数
     */
    int count;


    // --------------构造方法--------------

    /**
     * 创建一个容量为 capacity 的阻塞队列
     *
     * @param capacity 队列容量
     */
    public FArrayBlockingQueue(int capacity) {
        this(capacity, false);
    }

    /**
     * 创建一个容量为 capacity 的阻塞队列
     *
     * @param capacity 队列容量
     * @param fair     是否公平
     */
    public FArrayBlockingQueue(int capacity, boolean fair) {
        if (capacity <= 0) {
            throw new IllegalArgumentException();
        }
        this.items = new Object[capacity];
        lock = new ReentrantLock(fair);
        notEmpty = lock.newCondition();
        notFull = lock.newCondition();
    }

    // --------------核心方法--------------

    // 阻塞 + 异常
    @Override
    public void put(E e) throws InterruptedException {
        checkNotNull(e);
        ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            // 循环 唤醒+判断
            while (count == items.length) {
                notFull.await();
            }
            enqueue(e);
        } finally {
            lock.unlock();
        }
    }

    @Override
    public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0) {
                notEmpty.await();
            }
            return dequeue();
        } finally {
            lock.unlock();
        }
    }

    @Override
    public boolean offer(E e) {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            if (count == items.length) {
                return false;
            } else {
                enqueue(e);
                return true;
            }
        } finally {
            lock.unlock();
        }
    }

    @Override
    public E poll() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return (count == 0) ? null : dequeue();
        } finally {
            lock.unlock();
        }
    }

    @Override
    public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException {
        checkNotNull(e);
        long nanos = unit.toNanos(timeout);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == items.length) {
                if (nanos <= 0) {
                    return false;
                }
                nanos = notFull.awaitNanos(nanos);
            }
            enqueue(e);
            return true;
        } finally {
            lock.unlock();
        }
    }

    @Override
    public E poll(long timeout, TimeUnit unit) throws InterruptedException {
        long nanos = unit.toNanos(timeout);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0) {
                if (nanos <= 0) {
                    return null;
                }
                nanos = notEmpty.awaitNanos(nanos);
            }
            return dequeue();
        } finally {
            lock.unlock();
        }
    }

    @Override
    public E peek() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return itemAt(takeIndex);
        } finally {
            lock.unlock();
        }
    }

    // --------------非核心方法--------------

    @Override
    public int size() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return this.count;
        } finally {
            lock.unlock();
        }
    }

    @Override
    public int remainingCapacity() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return items.length - count;
        } finally {
            lock.unlock();
        }
    }

    /**
     * 添加元素
     *
     * @param e 添加的元素
     */
    private void enqueue(E e) {
        final Object[] items = this.items;
        items[putIndex] = e;
        // 环形队列
        if (++putIndex == items.length) {
            putIndex = 0;
        }
        count++;
        // 唤醒因队列为空而等待的取元素线程
        notEmpty.signal();
    }

    /**
     * 获取元素
     *
     * @return 获取的元素
     */
    private E dequeue() {
        final Object[] items = this.items;
        @SuppressWarnings("unchecked")
        E x = (E) items[takeIndex];
        // 元素位置清空
        items[takeIndex] = null;
        if (++takeIndex == items.length) {
            takeIndex = 0;
        }
        count--;
        notFull.signal();
        return x;
    }

    /**
     * 获取指定index元素
     *
     * @param takeIndex 索引
     * @return 元素
     */
    @SuppressWarnings("unchecked")
    private E itemAt(int takeIndex) {
        return (E) items[takeIndex];
    }

    /**
     * Throws NullPointerException if argument is null.
     *
     * @param v the element
     */
    private static void checkNotNull(Object v) {
        if (v == null) {
            throw new NullPointerException();
        }
    }

    // --------------未实现方法--------------

    @Override
    public Iterator<E> iterator() {
        throw new UnsupportedOperationException();
    }


    @Override
    public int drainTo(Collection<? super E> c) {
        return 0;
    }

    @Override
    public int drainTo(Collection<? super E> c, int maxElements) {
        return 0;
    }

}
